import { payment_data, payment_map } from '../../utils/dataset/db_data'

Page({
  data: {
    orderId: '',
    price: 0,
    payment_type: [],
    stadiumName: '',
    dateStr: '',
    lockSubmit: 0,
  },
  onLoad(options) {
    this.setData({ price: parseInt(options.price), payment_type: payment_data, stadiumName: options.stadiumName, dateStr: options.dateStr, orderId: options.orderId });
  },
  async onPay() {
    if (!(await this.checkFingerPrint())) return;
    this.setData({ lockSubmit: 1 });
    // 1. 检查余额，扣款，余额变动
    let res = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_balance',
        data: {
          funcName: 'transfer',
          payee_id: '<system>',
          price: this.data.price,
          remark: `预约缴费 【${this.data.stadiumName} ${this.data.dateStr}】`,
        },
        success: (r) => resolve(r.result)
      })
    })
    if (res.errMsg != '') {
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      })
      this.setData({ lockSubmit: 0 });
      return;
    }
    // 2. 订单更新、订单变动
    res = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_order',
        data: {
          funcName: 'update',
          order_id: this.data.orderId,
          updData: { order_state: 2, payment_type: 0, payment_time: new Date().getTime() }
        },
        success: (r) => resolve(r.result)
      })
    })
    if (!res.stats.updated) {
      wx.showToast({
        title: '订单状态变更失败',
        icon: 'none'
      })
      this.setData({ lockSubmit: 0 });
      return;
    }
    // 3. 预约变更
    await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_appointment',
        data: {
          funcName: 'changeStatus',
          order_id: this.data.orderId,
          status: 1
        },
        success: (r) => resolve(r.result)
      })
    })
    // 4. 生成核销卡券、卡券变动
    await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_coupon',
        data: {
          funcName: 'insert',
          order_id: this.data.orderId,
        },
        success: (r) => resolve(r.result)
      })
    })
    wx.navigateBack({
      delta: 1,
      success() {
        wx.redirectTo({
          url: `/pages/user/order/detail?orderId=${this.data.orderId}`,
        })
      }
    })
  },
  async checkFingerPrint() {
    const hasFingerPrint = await new Promise(resolve => {
      wx.checkIsSupportSoterAuthentication({
        success(r) {
          resolve(r.supportMode.includes('fingerPrint'))
        },
        fail() { resolve(false) }
      })
    })
    if (!hasFingerPrint) return 1;
    return await new Promise(resolve => {
      wx.startSoterAuthentication({
        requestAuthModes: ['fingerPrint'],
        challenge: '123456',
        authContent: '请使用指纹确认支付',
        success(res) { resolve(1) },
        fail(res) {
          wx.showToast({
            title: '指纹识别失败',
            icon: 'none'
          })
          resolve(0)
        }
      })
    })
  }
})